package com.astrocsr.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import com.astrocsr.business.SystemManager;
import com.astrocsr.business.UserManager;
import com.astrocsr.common.Constants;
import com.astrocsr.common.helper.ConfigHelper;
import com.astrocsr.domain.web.ParametersInfo;

public class AuthenticationFailureHandler extends
SimpleUrlAuthenticationFailureHandler {

	public AuthenticationFailureHandler() {
	}

	private @Autowired
	SystemManager systemManager;
	private @Autowired
	UserManager userManager;
	
	@Override
	public void onAuthenticationFailure(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException auth)
			throws IOException, ServletException {
		try {
			System.out.println("Catch Failure Login");
			String exceptionMsg = auth.getMessage();
			String[] messages = auth.getMessage().split(Constants.SPLIT);
			if (messages.length == 2) {
				String j_username = messages[0];
				exceptionMsg      = messages[1];
				System.out.println("j_username = " + j_username);
				
				// check password bad attempt
				int pwdBadAttemptCount 	= 1;
				int pwdBadAttemptMax 	= -1;
				String pwdBadAttemptKey = Constants.PARAM_PWD_BAD_ATTEMP + "_" + j_username;
				
				try {
					ParametersInfo parametersInfo = systemManager.getParameters(Constants.PARAM_NAME_TECH, Constants.PARAM_PWD_BAD_ATTEMP);
					if (parametersInfo != null) {
						pwdBadAttemptMax = Integer.parseInt(parametersInfo.getParamValue());
					} else {
						pwdBadAttemptMax = Constants.PARAM_PWD_BAD_ATTEMP_DEFAULT;
					}
					
					if (request.getSession().getAttribute(pwdBadAttemptKey) != null) {
						Integer pwdBadAtpsTmp = (Integer)request.getSession().getAttribute(pwdBadAttemptKey);
						pwdBadAttemptCount += pwdBadAtpsTmp;
					}	
				} catch (Exception e) {
					e.printStackTrace();
				}
	
				if (pwdBadAttemptMax > 0 && pwdBadAttemptCount >= pwdBadAttemptMax) {
					// lock user
					userManager.lockUser(j_username);
					request.getSession().removeAttribute(pwdBadAttemptKey);
					exceptionMsg = ConfigHelper.getInstance().get("system.authentication.locked");						
				} else {
					request.getSession().setAttribute(pwdBadAttemptKey, pwdBadAttemptCount);
				}
			}
			auth = new BadCredentialsException(exceptionMsg);
			super.onAuthenticationFailure(request, response, auth);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
